package io.rong.app.activity;

import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.enterplorer.R;

import java.util.List;

import io.rong.app.DemoContext;
import io.rong.app.model.RongEvent;
import io.rong.common.RLog;
import io.rong.imkit.widget.AsyncImageView;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;
import io.rong.message.LocationMessage;

/**
 * Created by zhjchen on 8/12/15.
 */
public class LocationMapActivity extends BasicMapActivity implements
        GeocodeSearch.OnGeocodeSearchListener, AMap.OnCameraChangeListener, AMap.OnMarkerClickListener, AMapLocationListener, LocationSource, View.OnClickListener {

    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private Location mInitLocation = null;
    private GeocodeSearch mGeocoderSearch = null;
    private LocationMessage mMsg = null;
    private YspTitleBar mTitleBar;

    private TextView mLocationErrText;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);

    @Override
    protected void initData() {

        Log.e("locationActivity", "---------init-------------");
    }

    @Override
    protected MapView initView(Bundle savedInstanceState) {

        MapView mapView = (MapView) findViewById(R.id.map);
        mTitleBar = (YspTitleBar)findViewById(R.id.title_bar);

        if (getIntent().hasExtra("location")) {
            LocationMessage msg = getIntent().getParcelableExtra("location");
            mTitleBar.setTitle(msg.getPoi());
            mInitLocation = new Location("");
            mInitLocation.setLongitude(msg.getLng());
            mInitLocation.setLatitude(msg.getLat());
        } else {
            mTitleBar.setSubTitle("确认");
            mTitleBar.setSubTitleClickListener(this);
            mGeocoderSearch = new GeocodeSearch(this);
            mGeocoderSearch.setOnGeocodeSearchListener(this);
        }

        mLocationErrText = (TextView)findViewById(R.id.location_errInfo_text);
        mLocationErrText.setVisibility(View.GONE);

        return mapView;
    }

    @Override
    protected void setUpMap() {
        aMap.setOnCameraChangeListener(this);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        setupLocationStyle();
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    @Override
    public void onClick(View v) {
        if (mMsg != null) {
            DemoContext.getInstance().getLastLocationCallback().onSuccess(mMsg);
            DemoContext.getInstance().setLastLocationCallback(null);
            finish();
        } else {
            DemoContext.getInstance().getLastLocationCallback()
                    .onFailure("定位失败");
        }
    }

    private void setupLocationStyle(){
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.drawable.gps_point));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(STROKE_COLOR);
        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(5);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(FILL_COLOR);
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_location;
    }

    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }


    public void onEventMainThread(RongEvent.RealTimeLocationJoinEvent event) {

    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mLocationErrText.setVisibility(View.GONE);
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                deactivate();
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
                mLocationErrText.setVisibility(View.VISIBLE);
                mLocationErrText.setText(errText);
            }
        }
    }

    public void addMarker(LatLng latLng, final UserInfo userInfo) {

        final String url = userInfo.getPortraitUri().toString();
        Log.d("LocationMapActivity", "LocationMapActivity addMarker-- url:" + url);

        final MarkerOptions markerOption = new MarkerOptions();

        markerOption.position(latLng);

        View view = LayoutInflater.from(this).inflate(R.layout.rc_icon_rt_location_marker, null);
        AsyncImageView imageView = (AsyncImageView) view.findViewById(android.R.id.icon);
        ImageView locImageView = (ImageView) view.findViewById(android.R.id.icon1);

        if (userInfo.getUserId().equals(RongIMClient.getInstance().getCurrentUserId())) {
            locImageView.setImageResource(R.drawable.rc_rt_loc_myself);
        } else {
            locImageView.setImageResource(R.drawable.rc_rt_loc_other);
        }

        imageView.setResource(url, 0);

        markerOption.anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory.fromView(view));

        Marker marker = getaMap().addMarker(markerOption);
        marker.setObject(userInfo.getUserId());

        RLog.e("addMarker", "addMarker:userId---" + userInfo.getUserId());
    }

    public void removeMarker(String userId) {

        RLog.e("removeMarker", "removeMarker:userId---" + userId);

        List<Marker> markers = getaMap().getMapScreenMarkers();

        for (Marker marker : markers) {
            RLog.e("removeMarker", "removeMarker:getObject---" + marker.getObject());
            if (marker.getObject() != null && userId.equals(marker.getObject())) {
                marker.remove();
                break;
            }
        }
        RLog.e("removeMarker", "------------------end");
    }


    public void moveMarker(final LatLng latLng, final UserInfo userInfo) {
        removeMarker(userInfo.getUserId());
        addMarker(latLng, userInfo);
    }

    /**
     * 对marker标注点点击响应事件
     */
    @Override
    public boolean onMarkerClick(final Marker marker) {
        return true;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        deactivate();
    }


    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mInitLocation != null) {
            mListener.onLocationChanged(mInitLocation);
            aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
            return;
        }
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onCameraChange(CameraPosition var1) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition var1) {
        if (mGeocoderSearch != null) {
            LatLng location = var1.target;
            LatLonPoint point = new LatLonPoint(location.latitude, location.longitude);
            RegeocodeQuery query = new RegeocodeQuery(point, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
            mGeocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
        }
    }

    /**
     * 地理编码查询回调
     */
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
    }

    /**
     * 逆地理编码回调
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
//        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
//            if (result != null && result.getRegeocodeAddress() != null
//                    && result.getRegeocodeAddress().getFormatAddress() != null) {
//                String addressName = result.getRegeocodeAddress().getFormatAddress();
//                LatLonPoint point = result.getRegeocodeQuery().getPoint();
//                Uri uri = Uri
//                    .parse("http://apis.map.qq.com/ws/staticmap/v2").buildUpon().appendQueryParameter("size", "240*240")
//                    .appendQueryParameter("key", "7JYBZ-4Y3W4-JMUU7-DJHQU-NOYH7-SRBBU").appendQueryParameter("zoom", "16")
//                        .appendQueryParameter("center", point.getLatitude() + "," + point.getLongitude()).build();
//
//                mMsg = LocationMessage.obtain(point.getLatitude(), point.getLongitude(), addressName, uri);
//            } else {
//                ToastUtil.show(this, "对不起，没有搜索到相关数据！");
//            }
//        } else {
//            ToastUtil.showerror(this, rCode);
//        }
    }
}